﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DarkAngels.WoW.Library.Armory.Character;
using System.Drawing.Imaging;
using System.IO;
using System.Xml;

namespace SmartDeviceProject1.Controls
{
    public delegate void SetSelectedCharacter(Character c);

    public partial class CharacterListPanel : UserControl
    {
        PictureButton[] m_buttons = null;
        public CharacterListPanel()
        {
            InitializeComponent();
            AdjustContent();
            m_buttons = new PictureButton[] {
                this.addCharacterPictureButton,
                this.removeCharacterPictureButton,
                this.selectCharacterPictureButton
            };
            AdjustContent();
            LoadXmlData();
        }

        public SetSelectedCharacter CharacterSelectionMethod
        {
            get
            {
                return m_character;
            }
            set
            {
                m_character = value;
            }
        }
        SetSelectedCharacter m_character = null;

        private List<Character> m_characters = new List<Character>();
        public List<Character> Characters
        {
            get
            {
                return m_characters;
            }
            set
            {
                m_characters = value;
                this.characterListBox1.Items.Clear();
                foreach (Character c in m_characters)
                    this.characterListBox1.Items.Add(c);
            }
        }

        public Character SelectedCharacter
        {
            get
            {
                return this.characterListBox1.SelectedCharacter;
            }
        }

        void AdjustContent()
        {
            #region Adjust Action Buttons
            Image[] icons = new Image[] { 
                SmartDeviceProject1.Properties.Resources.blue_add,
                SmartDeviceProject1.Properties.Resources.blue_del,
                SmartDeviceProject1.Properties.Resources.blue_user
            };
            Image[] pressed_icons = new Image[] { 
                SmartDeviceProject1.Properties.Resources.yellow_add,
                SmartDeviceProject1.Properties.Resources.yellow_del,
                SmartDeviceProject1.Properties.Resources.yellow_user
            };
            ImageAttributes trans = new ImageAttributes();
            if(icons != null)
            trans.SetColorKey(GetTransparentColor(icons[0]), GetTransparentColor(icons[0]));
            if (m_buttons != null)
            {
                int width = (this.Width + 3 + m_buttons.Length);
                for (int i = 0; i < m_buttons.Count(); i++)
                {
                    m_buttons[i].Top = 0;
                    m_buttons[i].Left = ((width / m_buttons.Length) * i) - (i + 1);
                    m_buttons[i].Height = this.panel1.Height;
                    m_buttons[i].Width = (width / m_buttons.Length);
                    m_buttons[i].BackgroundImage = GenerateImageWithBackground(
                        ResizeImage(icons[i], 24, 24, trans),
                        SmartDeviceProject1.Properties.Resources.background_button_reverse,
                        m_buttons[i].Width,
                        m_buttons[i].Height
                    );
                    m_buttons[i].PressedImage = GenerateImageWithBackground(
                        ResizeImage(pressed_icons[i], 24, 24, trans),
                        SmartDeviceProject1.Properties.Resources.background_button,
                        m_buttons[i].Width,
                        m_buttons[i].Height
                    );
                    m_buttons[i].Text = "";
                    m_buttons[i].Height = this.panel1.Height;
                }
            }
            #endregion
        }

        private Image GenerateImageWithBackground(Image icon, Image background, int width, int height)
        {
            Bitmap work = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(work);
            int iconWidth = icon.Width;
            int iconHeight = icon.Height;
            int newIconX = ((width - iconWidth) / 2);
            int newIconY = ((height - iconHeight) / 2);
            g.DrawImage(background, 0, 0);
            ImageAttributes attrib = new ImageAttributes();
            Color transparent = GetTransparentColor(icon);
            attrib.SetColorKey(transparent, transparent);
            g.DrawImage(icon, new Rectangle(newIconX, newIconY, icon.Width, icon.Height), 0, 0, icon.Width, icon.Height, GraphicsUnit.Pixel, attrib);
            return work;
        }
        private Image ResizeImage(Image icon, int width, int height, ImageAttributes attrib)
        {
            Bitmap destination = new Bitmap(width, height);
            Rectangle sourceRectangle = new Rectangle(0, 0, icon.Width, icon.Height);
            Rectangle destinationRectangle = new Rectangle(0, 0, width, height);
            Graphics g = Graphics.FromImage(destination);
            g.DrawImage(icon, destinationRectangle, 0, 0, sourceRectangle.Width, sourceRectangle.Height, GraphicsUnit.Pixel, attrib);
            return destination;
        }
        private Color GetTransparentColor(Image image)
        {
            return ((Bitmap)image).GetPixel(0, 0);
        }

        private void CharacterListPanel_Resize(object sender, EventArgs e)
        {
            AdjustContent();
        }

        string m_documentFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        string m_xmlDocument = "wimo_characters.xml";
        void LoadXmlData()
        {
            m_characters = new List<Character>();
            string path = Path.Combine(m_documentFolder, m_xmlDocument);
            if (File.Exists(path))
            {
                using(StreamReader sr = new StreamReader(File.OpenRead(path))) {
                    string str = sr.ReadToEnd();
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(str);
                    m_characters = new List<Character>();
                    m_characters.Clear();
                    XmlNodeList xmlCharacters = xmlDoc.SelectNodes("/data/character");
                    foreach (XmlNode node in xmlCharacters)
                    {
                        string name = node.SelectSingleNode("./name").InnerText, realm = node.SelectSingleNode("./realm").InnerText;
                        int region = Int32.Parse(node.SelectSingleNode("./region").InnerText);
                        Character c = new Character(
                            name,
                            realm,
                            (DarkAngels.WoW.Library.Armory.ArmoryRegion)Enum.ToObject(typeof(DarkAngels.WoW.Library.Armory.ArmoryRegion), region)
                        );
                        c.Load();
                        m_characters.Add(c);
                    }
                    this.Characters = m_characters;
                }
            }
        }
        void SaveXmlData()
        {
            string path = Path.Combine(m_documentFolder, m_xmlDocument);
            if (File.Exists(path))
                File.Delete(path);

            XmlTextWriter writer = new XmlTextWriter(path, Encoding.UTF8);
            writer.WriteStartDocument();
            writer.WriteStartElement("data");
            //go through all characters i nthe list and write those
            foreach (Character c in m_characters)
            {
                writer.WriteStartElement("character");
                writer.WriteStartElement("name");
                writer.WriteString(c.CharacterName);
                writer.WriteEndElement(); //ends 'writer.WriteStartElement("name");'

                writer.WriteStartElement("realm");
                writer.WriteString(c.RealmName);
                writer.WriteEndElement(); //ends 'writer.WriteStartElement("realm");'

                writer.WriteStartElement("region");
                writer.WriteString(((int)c.Region).ToString());
                writer.WriteEndElement(); //ends 'writer.WriteStartElement("region");'
                writer.WriteEndElement(); //ends 'writer.WriteStartElement("character");'
            }
            writer.WriteEndElement(); //ends 'writer.WriteStartElement("data");'
            writer.WriteEndDocument();

            writer.Flush();
            writer.Close();
        }

        public void ReadXml()
        {
            LoadXmlData();
        }

        public void SaveXml()
        {
            SaveXmlData();
        }

        private void addCharacterPictureButton_Click(object sender, EventArgs e)
        {
            SaveXmlData();
        }

        private void selectCharacterPictureButton_Click(object sender, EventArgs e)
        {
            if (m_character != null)
            {
                m_character(characterListBox1.SelectedCharacter);
            }
        }
    }
}
